package com.ryan.security.async;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;

/**
 * Created by kaimin on 1/1/2019.
 * time : 14:15
 */
@RestController
@Slf4j
public class AsyncController {

    @Autowired
    private MockQueue queue;


    @Autowired
    private DeferredResultHolder holder;

    @RequestMapping("order2")
    public DeferredResult<String> get2(){
        log.info("主线程开始");

        String orderNum= RandomStringUtils.randomNumeric(8);
        queue.setPlaceOrder(orderNum);

        DeferredResult<String> deferredResult= new DeferredResult<>();

        holder.getMap().put(orderNum,deferredResult);


        log.info("主线程返回");
        return deferredResult;
    }



    @RequestMapping("order")
    public Callable<String> get(){
        log.info("主线程开始");
        Callable<String> res=null;
        try {
            res=new Callable<String>() {
                @Override
                public String call() throws Exception {
                    log.info("副线程开始");
                    Thread.sleep(1000);
                    log.info("副线程结束");
                    return "成功购买";
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("主线程返回");
        return res;
    }


}
